<template>

	<Page title="人员管理" class="data-management-page">
		<template #body>
			<van-pull-refresh v-model="main.pullRefresh" @refresh="onRefresh">

				<div class="action-toolbar">
					<div>{{ `总计 ${main.peopleLibrary.size} 人` }}</div>

					<div class="action-buttons">
						<van-button type="primary" size="small" class="action-btn" @click="main.showDialog = true">
							<i class="fas fa-user-plus"></i>
							增员
						</van-button>
						<van-button type="primary" size="small" class="action-btn" @click="peopleSort">
							<i class="fas fa-arrow-down-wide-short"></i>
							排序
						</van-button>
					</div>
				</div>

				<van-grid :gutter="10" :column-num="4" square class="grid">
					<van-grid-item v-for="(value, index) in ([...main.peopleLibrary] as string[])" :key="value"
						icon="user-circle-o" :text="value" @click="peopleOptions(index)">
						<template #default>
							<div class="info">
								<van-icon name="user-circle-o" />
								<span>{{ value }}</span>
							</div>
							<div class="options" ref="peopleRefs">
								<van-button size="mini" type="danger"
									@click.stop="peopleOptionsDelete(value, index)">删除</van-button>
								<van-button size="mini" type="default"
									@click.stop="peopleOptionsCancel(index)">取消</van-button>
							</div>
						</template>
					</van-grid-item>
				</van-grid>

				<van-dialog v-model:show="main.showDialog" title="新增人员" show-cancel-button @confirm="addPeople"
					@cancel="closeDialog">
					<van-field v-model="main.peopleName" label="姓名" placeholder="请输入姓名..." clearable autofocus
						:label-width="usePxToVwView(50)" left-icon="user-circle-o" maxlength="8" />
				</van-dialog>
			</van-pull-refresh>
		</template>
	</Page>
</template>

<script setup lang="ts" name="TravelPeopleManagement">
import usePxToVwView from "@/hooks/usePxTransform"
import TravelRecordLibraryStore from "@/store/TravelRecordLibraryStore"
import { showFailToast, showSuccessToast, showToast } from "vant"
import { ref } from "vue"
import { reactive } from "vue"
import { TTravelInfo } from "../AddTravelRecord/AddTravelRecord"
import * as indexedDB from '@utility/indexedDB'
import { DB } from "@/assets/global"
import { exportTravelInfos } from "../SystemDataManagement/exportDataUtil"

const main = reactive({
	showDialog: false,
	peopleName: "",
	peopleLibrary: new Set<String>(),
	overlay: "none",
	pullRefresh: false
})
const store = TravelRecordLibraryStore()
const peopleRefs = ref()


const peopleSort = async () => {
	try {
		// 获取所有出差记录
		const result = (await indexedDB.queryAll(
			DB.store.TravelRecord.name
		)) as TTravelInfo[]

		// 处理数据并分析出差频率
		const finalResult = exportTravelInfos(result)
		const sortResult = analyzeTravelFrequency(finalResult)

		// 合并排序结果与原人员库
		store.PeopleLibrary = mergePeopleLists(sortResult, store.PeopleLibrary)
		showSuccessToast({ message: `按出差频率排序成功`, duration: 5000 })
	} catch (error) {
		console.error('人员排序出错:', error)
		showFailToast({ message: `人员排序出错: ${error}`, duration: 5000 })
	}
}

interface PersonTravelCount {
	name: string
	count: number
}

/**
 * 分析出差频率并返回排序后的数组
 * @param records 出差记录数组
 * @returns 按出差次数降序排列的人员数组
 */
function analyzeTravelFrequency(records: TTravelInfo[]): PersonTravelCount[] {
	// 创建人员出差次数统计对象
	const frequencyMap: Record<string, number> = {}

	// 遍历所有记录统计每人出差次数
	records.forEach(record => {
		record.travelPeople.forEach(person => {
			if (frequencyMap[person.name]) {
				frequencyMap[person.name]++
			} else {
				frequencyMap[person.name] = 1
			}
		})
	})

	// 转换为数组并排序
	const result = Object.entries(frequencyMap)
		.map(([name, count]) => ({ name, count }))
		.sort((a, b) => b.count - a.count)

	return result
}

/**
 * 合并排序结果与原人员库
 * @param sortedPeople 按出差频率排序的人员数组
 * @param originalPeople 原人员库数组
 * @returns 合并后的有序人员数组
 */
function mergePeopleLists(
	sortedPeople: PersonTravelCount[],
	originalPeople: string[]
): string[] {
	// 创建已排序人员名称集合
	const sortedNames = new Set(sortedPeople.map(item => item.name))

	// 过滤出原库中未出现在排序结果中的人员
	const remainingPeople = originalPeople.filter(name => !sortedNames.has(name))

	// 合并结果：排序人员 + 原库剩余人员（保持原顺序）
	return [
		...sortedPeople.map(item => item.name),
		...remainingPeople
	]
}


const onRefresh = () => {
	autoGetPeopleLibrary()
	main.pullRefresh = false
	showToast({
		message: "刷新成功",
		position: "top",
	})
}

const peopleOptionsDelete = (peopleName: string, index: number) => {
	main.peopleLibrary.delete(peopleName)
	store.PeopleLibrary.splice(index, 1)
	peopleRefs.value[index].style.display = "none"
	showToast({
		message: "删除成功",
		position: "top",
	})
}

const peopleOptionsCancel = (index: number) => {
	peopleRefs.value[index].style.display = "none"
}

const peopleOptions = (index: number) => {
	const display = peopleRefs.value[index].style.display
	if (display == "" || display == "none") {
		peopleRefs.value[index].style.display = "flex"
	}
	peopleRefs.value.forEach((el: any, idx: number) => {
		if (idx != index) {
			el.style.display = "none"
		}
	})
}

const closeDialog = () => {
	main.showDialog = false
	main.peopleName = ""
}

const addPeople = () => {
	if (main.peopleLibrary.has(main.peopleName)) {
		showFailToast(`【${main.peopleName}】\n已存在`)
		return
	}
	main.peopleLibrary.add(main.peopleName)
	store.PeopleLibrary.push(main.peopleName)
	showSuccessToast(`【${main.peopleName}】\n新增成功`)
	closeDialog()
}

const autoGetPeopleLibrary = () => {
	main.peopleLibrary = new Set(store.PeopleLibrary)
}
autoGetPeopleLibrary()
</script>

<style scoped lang="scss">
::v-deep(.van-pull-refresh) {
	overflow: unset;
}

.action-toolbar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8px 12px;
	background-color: white;
	border-radius: 8px;
	margin: 12px 0;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

	.action-buttons {
		display: flex;
		gap: 8px;
	}
}

.grid {

	.info {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 15px;

		.van-icon {
			font-size: 28px;
			margin-bottom: 3px;
		}
	}

	.options {
		width: 100%;
		height: 100%;
		position: absolute;
		background: rgba($color: #000000, $alpha: 0.4);
		display: none;
		flex-direction: column;
		align-items: center;
		justify-content: space-evenly;

		button {
			margin: 0;
			padding: 2px 10px;
		}
	}
}
</style>
